package cn.edu.sdufe.sn20180664257;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

/**
 * 第二次作业 toast显示复选框显示内容 实现源码
 */
public class Activity_ch5_2 extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

//    初始化一个ArrayList用于暂存已经选中的复选框
    private ArrayList arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_ch5_2);
//        初始化arrayList
        arrayList = new ArrayList();
//        先找到整个界面的容器
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ch5_2_ll);
//        遍历容器中的所有子元素
        int count = linearLayout.getChildCount();//查看子元素个数
        for (int i = 0; i < count; i ++){
            View view = linearLayout.getChildAt(i);//获取遍历的元素
            //区分是否为复选框
            if (view instanceof CheckBox){
                //强制类型转换并直接设置监听器
                CheckBox checkBox = (CheckBox) view;
                checkBox.setOnCheckedChangeListener(this);
            }
        }
    }

    @Override
    /**
     * 实现CompoundButton.OnCheckedChangeListener接口的onCheckedChanged方法
     */
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked){
            arrayList.add(buttonView);
        } else {
            arrayList.remove(buttonView);
        }
        String all = "您选择了:";
        int size = arrayList.size();
        //arrylist始终保存着已选中的复选框
        for (int i = 0; i < size; i ++){
            //遍历所有元素,合并为一个字符串
            CheckBox checkBox = (CheckBox)arrayList.get(i);
            String content = checkBox.getText().toString();
            all += content + ", ";
        }
        String a = size + "";
        String finaltoast = all + "共" + a + "项";
        Toast toast = Toast.makeText(this, finaltoast, Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);//setGravity方法用来设置位置（常量，水平方向偏移量，竖直方向偏移量）
        toast.setGravity(Gravity.CENTER, 0, 0);//多个常量之间用或“|”运算符，偏左和顶部显示，实现在左上角显示
        toast.show();
    }
}
